package com.sayimo.maker.mall.orders.service.impl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.sayimo.framework.common.Constants;
import com.sayimo.framework.common.util.VerifyCodeUtil;
import com.sayimo.framework.common.util.Date.DateUtil;
import com.sayimo.framework.exception.DaoException;
import com.sayimo.framework.exception.ServiceException;
import com.sayimo.maker.commons.Constant;
import com.sayimo.maker.commons.utils.JSONUtil;
import com.sayimo.maker.mall.goods.service.GoodsNormsStockInterfaceService;
import com.sayimo.maker.mall.goods.service.GoodsNormsValueStockInterfaceService;
import com.sayimo.maker.mall.goods.vo.GoodsNormsStock;
import com.sayimo.maker.mall.orders.dao.OrderReturnFlowDao;
import com.sayimo.maker.mall.orders.dao.OrderReturnModeDao;
import com.sayimo.maker.mall.orders.dao.OrderReturnRefDao;
import com.sayimo.maker.mall.orders.service.OrderReturnFlowService;
import com.sayimo.maker.mall.orders.service.OrdersFlowInterfaceService;
import com.sayimo.maker.mall.orders.service.OrdersGoodsInfoInterfaceService;
import com.sayimo.maker.mall.orders.service.OrdersListInterfaceService;
import com.sayimo.maker.mall.orders.service.OrdersReceivingAddressInterfaceService;
import com.sayimo.maker.mall.orders.service.OrdersReturnRefService;
import com.sayimo.maker.mall.orders.service.OrdersReturnService;
import com.sayimo.maker.mall.orders.vo.OrderReturnFlow;
import com.sayimo.maker.mall.orders.vo.OrderReturnMode;
import com.sayimo.maker.mall.orders.vo.OrderReturnRef;
import com.sayimo.maker.mall.orders.vo.OrdersFlow;
import com.sayimo.maker.mall.orders.vo.OrdersGoodsInfo;
import com.sayimo.maker.mall.orders.vo.OrdersList;
import com.sayimo.maker.mall.orders.vo.OrdersReceivingAddress;
import com.sayimo.maker.user.service.WalletIncomeExpendRecordService;
import com.sayimo.maker.user.service.WalletInterfaceService;
import com.sayimo.maker.user.vo.Wallet;
import com.sayimo.maker.user.vo.WalletIncomeExpendRecord;



/**
 * @Project: schoolmallapi2.0
 * @ClassName: OrdersReturnServiceImpl
 * @Description: 
 * @author:	chenpy
 * @date:	2016年6月14日
 * @version 1.0.0
 */
@Service("ordersReturnService")
public class OrdersReturnServiceImpl implements OrdersReturnService {
	
	@Autowired(required=false)
	private HttpServletRequest request;
	
	@Resource(name="orderReturnRefDao")
	private OrderReturnRefDao orderReturnRefDao;
	
	@Resource(name="ordersListInterfaceService")
	private OrdersListInterfaceService ordersListInterfaceService;
	
	@Resource(name="orderReturnFlowDao")
	private OrderReturnFlowDao orderReturnFlowDao;
	
	@Resource(name="orderReturnModeDao")
	private OrderReturnModeDao orderReturnModeDao;
	
//	@Resource(name="walletIncomeExpendRecordDaoImpl")
//	private WalletIncomeExpendRecordDao walletIncomeExpendRecordDao;
	@Autowired
	private WalletIncomeExpendRecordService walletIncomeExpendRecordService;
	
	
//	@Resource(name="walletDaoImpl")
//	private WalletDao walletDao;
    @Resource
	private WalletInterfaceService walletInterfaceService;
	
	@Autowired
	private GoodsNormsValueStockInterfaceService goodsNormsValueStockService;
	@Autowired
	private GoodsNormsStockInterfaceService goodsNormsStockService;
	@Autowired
	private OrdersGoodsInfoInterfaceService ordersGoodsInfoInterfaceService;
	@Autowired
	private OrdersReceivingAddressInterfaceService ordersReceivingAddressInterfaceService;
	@Autowired
	private OrdersFlowInterfaceService ordersFlowInterfaceService;
	@Autowired
	private OrderReturnFlowService orderReturnFlowService;
	@Autowired
	private OrdersReturnRefService ordersReturnRefService;
	
	private static Log logger = LogFactory.getLog(OrdersReturnServiceImpl.class);
	
	public HttpServletRequest getRequest() {
		return request;
	}

	public void setRequest(HttpServletRequest request) {
		this.request = request;
	}

	/** 
	  * @package com.sayimo.school.mall.util
	  * @author chenpy
	  * @Title:  
	  * @Description: 申请退换货
	  * @param 
	  * @throws 
	  * @return void
	  * @date 2016年6月14日
	  */ 
	@SuppressWarnings("serial")
	public Map<String, Object> addApplyForReturnGoods(HttpServletRequest request) throws ServiceException {
		Map<String, Object> resultMap = new HashMap<>();
		
		String _ordersId = request.getParameter("ordersId");
		String _goodsId = request.getParameter("goodsId");
		String _normsValueId = request.getParameter("normsValueId");
		String _type = request.getParameter("type");
		String _photoIds = request.getParameter("photoIds");
		String _applyExplain = request.getParameter("applyExplain");
		String _customerId = request.getParameter("customerId");
		String _returnNum = request.getParameter("returnNum");
		String _transactionPrice = request.getParameter("transactionPrice");
		
		if (StringUtils.isEmpty(_ordersId) || StringUtils.isEmpty(_goodsId) || StringUtils.isEmpty(_normsValueId) || StringUtils.isEmpty(_type) || StringUtils.isEmpty(_applyExplain)
				|| StringUtils.isEmpty(_customerId) || StringUtils.isEmpty(_returnNum) || StringUtils.isEmpty(_transactionPrice)) {
			resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
			resultMap.put(Constant.ERROR_CODE, Constant.SYSTEM_REQUEST_PARAM_ERROR);
			return resultMap;
		}
		
		// 判断订单是否存在
		OrdersList ordersList = ordersListInterfaceService.queryOrdersListById(Integer.parseInt(_ordersId));
		if (ordersList == null) { // 订单不存在
			resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
			resultMap.put(Constant.ERROR_CODE, Constant.ORDERS_NOT_EXISTS);	
			return resultMap;
		}
		
		// 判断订单状态，只有已发货订单才能进行退换货
		if (ordersList.getStatus() != 3) {
			resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
			resultMap.put(Constant.ERROR_CODE, Constant.ORDERS_RETURN_STATUS_ERROR_FOR_RETURN);	
			return resultMap;
		}
		
		OrderReturnRef orderReturnRef = new OrderReturnRef();
		orderReturnRef.setApplyExplain(_applyExplain);
		orderReturnRef.setOrderId(Integer.parseInt(_ordersId));
		orderReturnRef.setCustomerId(Integer.parseInt(_customerId));
		orderReturnRef.setGoodsId(Integer.parseInt(_goodsId));
		orderReturnRef.setNormsValueId(Integer.parseInt(_normsValueId));
		orderReturnRef.setPhotoIds(_photoIds);
		orderReturnRef.setReturnGoodsNum(Integer.parseInt(_returnNum));
		orderReturnRef.setType(Integer.parseInt(_type));
		orderReturnRef.setTotalMoeny(new BigDecimal(orderReturnRef.getReturnGoodsNum() * Double.valueOf(_transactionPrice)));
		orderReturnRef.setOrderNo(System.currentTimeMillis() + VerifyCodeUtil.getNumberVerifyCode(4));
		orderReturnRef.setTransactionPrice(new BigDecimal(_transactionPrice));
		orderReturnRef.setStatus(1);
		try {
			orderReturnRefDao.insertOrderReturnRef(orderReturnRef);
			
			OrderReturnFlow flow = new OrderReturnFlow();
			flow.setCreateUser(Integer.parseInt(_customerId));
			flow.setReturnRefId(orderReturnRef.getId());
			flow.setUserType(2);
			
			orderReturnFlowDao.insertOrderReturnFlow(flow);
		} catch (DaoException e) {
			logger.error(e);
			throw new ServiceException(e);
		}
		
		resultMap.put(Constant.STATUS, Constant.STATUS_SUCCESS);
		resultMap.put(Constant.DATA, new HashMap<String,Object>(){{
			put(Constant.MSG, "申请成功");
		}});	
		
		return resultMap;
	}

	/** 
	  * @package com.sayimo.school.mall.module.order.service
	  * @author chenpy
	  * @Title:  addReturnEmsInfo
	  * @Description: 录入用户返货信息
	  * @param 
	  * @throws 
	  * @return Map<String,Object>
	  * @date 2016年6月17日
	  */
	@SuppressWarnings("serial")
	public Map<String, Object> addReturnEmsInfo(HttpServletRequest request) throws ServiceException {
		Map<String, Object> resultMap = new HashMap<>();
		// 判断参数
		String _customerId = request.getParameter("customerId");
		String _returnRefId = request.getParameter("returnRefId");
		String _type = request.getParameter("type");
		String _emsNo = request.getParameter("emsNo");
		String _emsId = request.getParameter("emsId");
		String _emsName = request.getParameter("emsName");
		logger.info("type = " + _type + ", _emsId = " + _emsId + ", emsNo = " + _emsNo + ", emsName = " + _emsName);
		if (StringUtils.isEmpty(_customerId) || StringUtils.isEmpty(_returnRefId) || StringUtils.isEmpty(_type)) {
			resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
			resultMap.put(Constant.ERROR_CODE, Constant.SYSTEM_REQUEST_PARAM_ERROR);
			return resultMap;
		}
		
		// 判断订单状态
		try {
			OrderReturnRef orderReturnRef = orderReturnRefDao.getOrderReturnRefById(Integer.parseInt(_returnRefId));
			// 商家已同意退换货申请，待用户还货
			if (orderReturnRef.getStatus() != 2) {
				resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
				resultMap.put(Constant.ERROR_CODE, Constant.ORDERS_RETURN_STATUS_ERROR_FOR_RETURN);
				return resultMap;
			}
			
			// 新增返货信息
			OrderReturnMode mode = new OrderReturnMode();
			mode.setReturnRefId(Integer.parseInt(_returnRefId));
			mode.setType(Integer.parseInt(_type));
			if (mode.getType() == 3) {
				// 查询物流公司
				mode.setEmsId(StringUtils.isNotEmpty(_emsId) ? Integer.parseInt(_emsId) : null);
				mode.setEmsName(_emsName);
				mode.setEmsNo(_emsNo);
			}
			orderReturnModeDao.insertOrderReturnMode(mode);
			
			// 修改退换货订单状态
			orderReturnRef.setStatus(3);
			orderReturnRefDao.updateOrderReturnRef(orderReturnRef);
			
			// 退换货订单流程
			OrderReturnFlow flow = new OrderReturnFlow();
			flow.setStatus(3);
			flow.setUserType(2);
			flow.setCreateUser(Integer.parseInt(_customerId));
			flow.setReturnRefId(orderReturnRef.getId());
			orderReturnFlowDao.insertOrderReturnFlow(flow);
			
			resultMap.put(Constant.STATUS, Constant.STATUS_SUCCESS);
			resultMap.put(Constant.DATA, new HashMap<String,Object>(){{
				put(Constant.MSG, "操作成功");
			}});	
			
			return resultMap;
		} catch (NumberFormatException | DaoException e) {
			logger.error(e);
			throw new ServiceException(e);
		}
	}

	/** 
	 * @package com.sayimo.school.mall.module.order.service
	 * @author 李强
	 * @Title:  getReturnOrderList
	 * @Description: 退换货订单列表
	 * @param 
	 * @throws 
	 * @return Map
	 * @date 2016年6月21日
	 */
	@SuppressWarnings({ "rawtypes", "unchecked"})
	public Map getReturnOrderList(String _customerId,Integer pageNow,Integer pageSize,String _status) throws ServiceException {
		Map resultMap = new HashMap();
		
		try {
			Integer customerId = null;
			Integer providerId = null;
			Integer status = null;
			if (_status!=null&&!"".equals(_status)) {
				status = Integer.valueOf(_status);
			}
			
				customerId = Integer.valueOf(_customerId);
				if(StringUtils.isEmpty(customerId.toString()) && StringUtils.isEmpty(pageNow.toString()) && 
						StringUtils.isEmpty(pageSize.toString())){//参数错误
					resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
					resultMap.put(Constant.ERROR, Constant.SYSTEM_REQUEST_PARAM_ERROR);
					return resultMap;
				}
			
			List<Map> returnOrderList=orderReturnRefDao.getReturnOrderList(customerId, status, providerId, (pageNow - 1) * pageSize, pageSize);
			if(returnOrderList != null&& returnOrderList.size()>0){
				for(Map map:returnOrderList){
					if(map.get("timesTamp") != null){
						Date date = (Date) map.get("timesTamp");
						map.put("timesTamp", date.getTime());
					}
					// 获取退换货订单下商品信息
					List returnGoodsList=orderReturnRefDao.getReturnGoodsList(Integer.valueOf(map.get("goodsId").toString()));
					map.put("goodsList", returnGoodsList);
				}
			}
			Map map = new HashMap();
			map.put("returnOrderList", returnOrderList);
			resultMap.put(Constant.DATA, map);
			resultMap.put(Constant.STATUS, Constant.STATUS_SUCCESS);
			
		} catch (DaoException e) {
			e.printStackTrace();
			logger.error(e);
			throw new ServiceException(e);
		}
		return resultMap;
	}

	/** 
	 * @package com.sayimo.school.mall.module.order.service
	 * @author 李强
	 * @Title:  getReturnOrderId
	 * @Description: 退换货订单详情
	 * @param 
	 * @throws 
	 * @return Map
	 * @date 2016年6月22日
	 */
	@SuppressWarnings({ "rawtypes", "unchecked"})
	public Map getReturnOrderId(Integer returnRefId) throws ServiceException {
		Map resultMap = new HashMap();
		try {
			Map map=new HashMap();
			if(StringUtils.isEmpty(returnRefId.toString())){//参数错误
				resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
				resultMap.put(Constant.ERROR, Constant.SYSTEM_REQUEST_PARAM_ERROR);
				return resultMap;
			}
			//查询退换货订单详情
			map = orderReturnRefDao.getReturnOrderId(returnRefId);
			if(map.size()==0){// 订单不存在
				resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
				resultMap.put(Constant.ERROR_CODE, Constant.ORDERS_NOT_EXISTS);	
				return resultMap;
			}
			//查询退换货商品信息
			List goods=orderReturnRefDao.getReturnGoodsList(Integer.valueOf(map.get("goodsId").toString()));
			if(goods != null&& goods.size()>0){
				map.put("goods", goods);
			}
			//查询快递公司信息
			OrderReturnMode orderReturnMode=orderReturnModeDao.selectOrderReturnId(returnRefId);
			/*if(orderReturnMode==null){//快递公司不存在
				resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
				resultMap.put(Constant.ERROR_CODE, Constant.SYSTEM_NO_DATA);	
				return resultMap;
			}else{*/
			map.put("emsInfo", orderReturnMode);
			/*}*/
			//查询原订单收货人信息
			Map receivePeople=orderReturnRefDao.getOrderReceivingReturnRefId(returnRefId);
			if(receivePeople.size()>0){
				map.put("receivePeople", receivePeople);
			}
			resultMap.put(Constant.DATA, map);
		} catch (DaoException e) {
			logger.error(e);
			throw new ServiceException(e);
		}
		return resultMap;
	}

	/** 
	  * @package com.sayimo.school.mall.module.order.service
	  * @author chenpy
	  * @Title:  confirmReturnedOrder
	  * @Description: 退换货确认收货
	  * @param 
	  * @throws 
	  * @return Map<String,Object>
	  * @date 2016年6月24日
	  */
	@SuppressWarnings("unchecked")
	public Map<String, Object> confirmReturnedOrder(HttpServletRequest request) throws ServiceException {
		Map<String, Object> resultMap = new HashMap<>();
		String _orderReturnId = request.getParameter("orderReturnId");
		String _customerId = request.getParameter("customerId");
		logger.info("_orderReturnId = " + _orderReturnId + ", _customerId = " + _customerId);
		if (StringUtils.isEmpty(_orderReturnId) || StringUtils.isEmpty(_customerId)) {
			resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
			resultMap.put(Constant.ERROR, Constant.SYSTEM_REQUEST_PARAM_ERROR);
			return resultMap;
		}
		
		try {
			Integer orderReturnId = Integer.parseInt(_orderReturnId);
			OrderReturnRef orderReturnRef = orderReturnRefDao.getOrderReturnRefById(orderReturnId);
			
			if (orderReturnRef == null) {
				resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
				resultMap.put(Constant.ERROR_CODE, Constant.ORDERS_NOT_EXISTS);	
				return resultMap;
			}
			
			// 订单状态错误
			if (orderReturnRef.getStatus() != 4) {
				resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
				resultMap.put(Constant.ERROR_CODE, Constant.ORDERS_RETURN_STATUS_ERROR_FOR_RETURN);	
				return resultMap;
			}
			
			// 完成新订单收货
			Map<String, Object> paramMap = new HashMap<>();
			paramMap.put("customerId", _customerId);
			paramMap.put("orderId", orderReturnRef.getNewOrderId());
			resultMap = ordersListInterfaceService.updateConfirmReceive(paramMap);
			
			// 订单流程表
			OrderReturnFlow flow = new OrderReturnFlow();
			flow.setStatus(7);
			flow.setUserType(2);
			flow.setCreateUser(Integer.parseInt(_customerId));
			flow.setReturnRefId(orderReturnRef.getId());
			orderReturnFlowDao.insertOrderReturnFlow(flow);
			
			// 修改退换货订单状态
			orderReturnRef.setStatus(5);
			orderReturnRefDao.updateOrderReturnRef(orderReturnRef);
			
			resultMap.put(Constant.STATUS, Constant.STATUS_SUCCESS);
			resultMap.put(Constant.DATA, new HashMap<String,Object>(){{
				put(Constant.MSG, "操作成功");
			}});
			
			
		} catch (DaoException e) {
			logger.error(e);
			throw new ServiceException(e);
		}
		return resultMap;
	}
	
	/** 
	  * @package com.sayimo.school.mall.module.order.service
	  * @author chenpy
	  * @Title:  
	  * @Description: 取消退换货
	  * @param 
	  * @throws 
	  * @return Map<String,Object>
	  * @date 2016年7月6日
	  */ 
	@SuppressWarnings("serial")
	public Map<String, Object> updateCancelOrdersReturn(HttpServletRequest request) throws ServiceException{
		Map<String, Object> resultMap = new HashMap<>();
		String _orderReturnId = request.getParameter("orderReturnId");
		String _customerId = request.getParameter("customerId");
		if (StringUtils.isEmpty(_orderReturnId) || StringUtils.isEmpty(_customerId)) {
			resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
			resultMap.put(Constant.ERROR, Constant.SYSTEM_REQUEST_PARAM_ERROR);
			return resultMap;
		}
		
		try {
			Integer orderReturnId = Integer.parseInt(_orderReturnId);
			OrderReturnRef orderReturnRef = orderReturnRefDao.getOrderReturnRefById(orderReturnId);
			if (orderReturnRef == null) {
				resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
				resultMap.put(Constant.ERROR_CODE, Constant.ORDERS_NOT_EXISTS);	
				return resultMap;
			}
			
			// 只有待审核状态的退换货订单才可以取消
			if (orderReturnRef.getStatus() != 1) {
				resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
				resultMap.put(Constant.ERROR_CODE, Constant.ORDERS_RETURN_STATUS_ERROR_FOR_RETURN);	
				return resultMap;
			}
			
			// 修改订单状态
			orderReturnRef.setStatus(-1);
			// 订单流程表
			OrderReturnFlow flow = new OrderReturnFlow();
			flow.setStatus(-1);
			flow.setUserType(2);
			flow.setCreateUser(Integer.parseInt(_customerId));
			flow.setReturnRefId(orderReturnRef.getId());
			orderReturnFlowDao.insertOrderReturnFlow(flow);
			
			// 修改退换货订单状态
			orderReturnRef.setStatus(-1);
			orderReturnRefDao.updateOrderReturnRef(orderReturnRef);
			
			resultMap.put(Constant.STATUS, Constant.STATUS_SUCCESS);
			resultMap.put(Constant.DATA, new HashMap<String,Object>(){{
				put(Constant.MSG, "操作成功");
			}});	
			
			return resultMap;
		} catch (NumberFormatException | DaoException e) {
			logger.error(e);
			throw new ServiceException(e);
		}
	}

	/** 
	 * @package com.sayimo.school.mall.service.ope
	 * @author wangyang
	 * @Title:  updateReceipt
	 * @Description: 退换货确认
	 * @param 
	 * @throws 
	 * @return Map
	 * @date 2016年7月15日
	 */ 
	@Override
	public Map<String, Object> updateReceipt() throws ServiceException {
		Map<String, Object> resultMap = new HashMap<>();
		String _returnRefId = request.getParameter("returnRefId");  //退换货表ID
		String _providerId = request.getParameter("providerId");    //供应商ID
		if (StringUtils.isEmpty(_returnRefId) || StringUtils.isEmpty(_providerId)) {
			resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
			resultMap.put(Constant.ERROR, Constant.SYSTEM_REQUEST_PARAM_ERROR);
			return resultMap;
		}
		try{
			Integer returnRefId=Integer.parseInt(_returnRefId);
			Integer providerId=Integer.parseInt(_providerId);
			OrderReturnRef validOrderReturnRef = orderReturnRefDao.getOrderReturnRefByIdAndProviderId(returnRefId,providerId);
			// 判断订单状态
			if (validOrderReturnRef.getStatus() != 3) {
				resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
				resultMap.put(Constant.ERROR, Constant.ORDERS_RETURN_STATUS_ERROR_FOR_RETURN);
				return resultMap;
			}
			//
			OrderReturnRef paramOrderReturnRef=new OrderReturnRef();
			
			paramOrderReturnRef.setId(returnRefId);
			paramOrderReturnRef.setOrderId(validOrderReturnRef.getOrderId());
			paramOrderReturnRef.setReturnGoodsNum(validOrderReturnRef.getReturnGoodsNum());
			paramOrderReturnRef.setCustomerId(validOrderReturnRef.getCustomerId());
			paramOrderReturnRef.setTotalMoeny(validOrderReturnRef.getTotalMoeny());
			paramOrderReturnRef.setGoodsId(validOrderReturnRef.getGoodsId());
			paramOrderReturnRef.setNormsValueId(validOrderReturnRef.getNormsValueId());
			paramOrderReturnRef.setType(validOrderReturnRef.getType());
			int type = paramOrderReturnRef.getType();
			// 退货->6已退货已完成，换货->4已生成换货新订单
			int status = type == 1 ? 6 : 4;
			
			// 退货
			if (type == 1) {
				updateOrderReturn(paramOrderReturnRef);
			}// 换货
			else{
				Integer newNormsValueId = Integer.parseInt(request.getParameter("newNormsValueId"));
				Integer emsId = Integer.parseInt(request.getParameter("emsId"));
				String emsNo = request.getParameter("emsNo");
				paramOrderReturnRef.setNewOrderNormsValueId(newNormsValueId);
				paramOrderReturnRef.setEmsId(emsId);
				paramOrderReturnRef.setEmsNo(emsNo);
				int newOrderId = updateOrderReplace(paramOrderReturnRef,providerId);
				paramOrderReturnRef.setNewOrderId(newOrderId);
			}
			// 修改原始订单信息（修改退换货商品状态、重新计算原订单金额）
//			updatePrimitiveOrderInfo(paramOrderReturnRef,providerId);
			
			// 退换货订单流程表
			OrderReturnFlow flow = new OrderReturnFlow();
			flow.setCreateUser(providerId);
//			flow.setReturnRefId(paramOrderReturnRef.getId());
			flow.setReturnRefId(returnRefId);
			flow.setUserType(2);
			flow.setStatus(status);
			orderReturnFlowService.insertReturnFlow(flow);
//			orderReturnFlowDao.insert("com.sayimo.school.mall.dao.ope.OrderReturnFlowDao.insertReturnFlow", flow);
			
			// 修改订单状态订单表
			paramOrderReturnRef.setStatus(status);
			ordersReturnRefService.updateOrderReturnRef(paramOrderReturnRef);
//			orderReturnRefDao.update("com.sayimo.school.mall.dao.ope.OrderReturnRefDao.updateOrderReturnRef", paramOrderReturnRef);
			
			resultMap.put(Constants.STATUS, Constants.SUCCESS);
			return resultMap;
		} catch (DaoException e) {
			logger.error(e);
			throw new ServiceException(e);
		}
	}
	
	/** 
	  * @package com.sayimo.school.mall.service.ope.impl
	  * @author wangyang
	  * @Title:  updateOrderReturn
	  * @Description: 退货返还钱包
	  * @param 
	  * @throws DaoException 
	  * @throws ServiceException 
	  * @throws 
	  * @return int
	  * @date 2016年7月15日
	  */ 
	private void updateOrderReturn(OrderReturnRef orderReturnRef) throws DaoException, ServiceException{
		WalletIncomeExpendRecord expendRecord = new WalletIncomeExpendRecord();
		expendRecord.setCustomerId(orderReturnRef.getCustomerId());
		expendRecord.setInCome(orderReturnRef.getTotalMoeny());
		expendRecord.setOrderType(0);
		expendRecord.setEmsNo(System.currentTimeMillis() + VerifyCodeUtil.getNumberVerifyCode(4));
		expendRecord.setFromType(2);
		expendRecord.setCommet("收到系统退款");
		//退还退货钱财
//		walletIncomeExpendRecordDao.insert("com.sayimo.school.mall.module.admin.dao.WalletIncomeExpendRecordInterfaceDao.insertIncomeExpendRecord", expendRecord);
		walletIncomeExpendRecordService.insertSelective(expendRecord);
		//获得会员钱包
//		Wallet wallet = walletDao.get("com.sayimo.school.mall.module.admin.dao.WalletInterfaceDao.queryWalletByCustomerId", orderReturnRef.getCustomerId());
		Wallet wallet =walletInterfaceService.queryWalletByCustomerId(orderReturnRef.getCustomerId());
	/*	wallet.setRemainingMoney(wallet.getRemainingMoney()+orderReturnRef.getTotalMoeny().doubleValue());
		wallet.setAvailableMoney(wallet.getAvailableMoney()+orderReturnRef.getTotalMoeny().doubleValue());*/
//		walletDao.update("com.sayimo.school.mall.dao.member.WalletDao.updateWallet", wallet);
		walletInterfaceService.updateWallet(wallet);
		// 修改商品库存数量
		Map<String, Object> paramMap = new HashMap<>();
		paramMap.put("goodsId", orderReturnRef.getGoodsId());
		paramMap.put("goodsNormsValueId", orderReturnRef.getNormsValueId());
		paramMap = goodsNormsValueStockService.getNormsValueStockByMap(paramMap);
		Integer stockId = Integer.parseInt(paramMap.get("stockId").toString());
		GoodsNormsStock goodsNormsStock = goodsNormsStockService.selectGoodsNormsStock(stockId);
		goodsNormsStock.setStockNum(goodsNormsStock.getStockNum() + orderReturnRef.getReturnGoodsNum());
		goodsNormsStockService.updateGoodsNormsStock(goodsNormsStock);
	}
	/** 
	  * @package com.sayimo.school.mall.service.ope.impl
	  * @author chenpy
	  * @Title:  updateOrderReplace
	  * @Description: 换货处理、并生成新订单
	  * @param 
	  * @throws ServiceException 
	  * @throws DaoException 
	  * @throws 
	  * @return int
	  * @date 2016年6月17日
	  */ 
	private int updateOrderReplace(OrderReturnRef paramOrderReturnRef,Integer providerId) throws ServiceException, DaoException {
		Integer newOrderNormsValueId = paramOrderReturnRef.getNewOrderNormsValueId();
		// 获取所选新商品规格信息
		Map<String, Object> paramMap = new HashMap<>();
		paramMap.put("goodsId", paramOrderReturnRef.getGoodsId());
		paramMap.put("goodsNormsValueId", newOrderNormsValueId);
		Map<String, Object> resultMap = goodsNormsValueStockService.getNormsValueStockByMap(paramMap);
		
		// 生成新商品订单
		OrdersList orders = new OrdersList();
		orders.setOrdersNo(System.currentTimeMillis() + VerifyCodeUtil.getNumberVerifyCode(4));
		orders.setStatus(3);
		orders.setCustomerId(paramOrderReturnRef.getCustomerId());

		orders.setTotalAmount(new BigDecimal(paramOrderReturnRef.getReturnGoodsNum()).multiply((BigDecimal)resultMap.get("preferentialPrice")));
		orders.setSumMoney(new BigDecimal(paramOrderReturnRef.getReturnGoodsNum()).multiply((BigDecimal)resultMap.get("preferentialPrice")));
		orders.setReturnLabel(1);
		orders.setEmsNo(paramOrderReturnRef.getEmsNo());
		orders.setEmsName(paramOrderReturnRef.getEmsName());
		orders.setEmsId(paramOrderReturnRef.getEmsId());
		orders.setSendDate(new Date());
		
//		int orderId = ordersService.insertOrdersList(orders);
		int orderId = ordersListInterfaceService.insertOrdersList(orders);
		// 订单下商品信息
		OrdersGoodsInfo goodsInfo = new OrdersGoodsInfo();
		goodsInfo.setOrdersId(orderId);
		goodsInfo.setGoodsId(paramOrderReturnRef.getGoodsId());
		goodsInfo.setNormsValueId(newOrderNormsValueId);
		goodsInfo.setBuyNum(paramOrderReturnRef.getReturnGoodsNum());
		goodsInfo.setSellPrice((BigDecimal)resultMap.get("originalPrice"));
		goodsInfo.setTransactionPrice((BigDecimal)resultMap.get("preferentialPrice"));
		goodsInfo.setGoodsFrom((String)resultMap.get("sendAddress"));

//		ordersGoodsInfoService.insertOrderGoodsInfo(goodsInfo);
		ordersGoodsInfoInterfaceService.insertPrivoderOrderGoodsInfo(goodsInfo);
		
		// 订单收货地址
//		OrdersReceivingAddress address = ordersReceivingAddressService.selectOrdersReceivingAddressByOrdersId(paramOrderReturnRef.getOrderId());
		OrdersReceivingAddress address = ordersReceivingAddressInterfaceService.queryOrderReceivingCountByOrdersId(paramOrderReturnRef.getOrderId());
		address.setOrdersId(orderId);
		
		Map<String, Object> paramAddress = JSONUtil.readValueToMap(JSONUtil.writeValueAsString(address));
		paramAddress.put("batchCode", generateBatchCode());
		//新增订单收货地址
//		ordersReceivingAddressService.insertOrdersReceivingAddress(paramAddress);
		ordersReceivingAddressInterfaceService.insertOrdersReceivingAddress(paramAddress);
		
		// 订单流程表
		OrdersFlow flow = new OrdersFlow();
		flow.setOrdersId(orderId);
		flow.setActionUser(providerId);
		flow.setStatus(3);
		flow.setActionUser(1);
		
		// 修改商品规格库存信息
		// 原商品规格+退换货数量
		paramMap = new HashMap<>();
		paramMap.put("goodsId", paramOrderReturnRef.getGoodsId());
		paramMap.put("goodsNormsValueId", paramOrderReturnRef.getNormsValueId());
		resultMap = goodsNormsValueStockService.getNormsValueStockByMap(paramMap);
		Integer stockId = Integer.parseInt(resultMap.get("stockId").toString());
		GoodsNormsStock goodsNormsStock = goodsNormsStockService.selectGoodsNormsStock(stockId);
		goodsNormsStock.setStockNum(goodsNormsStock.getStockNum() + paramOrderReturnRef.getReturnGoodsNum());
		goodsNormsStockService.updateGoodsNormsStock(goodsNormsStock);
		
		// 新选择的商品规格-退换货数量 
		paramMap = new HashMap<>(); 
		paramMap.put("goodsId", paramOrderReturnRef.getGoodsId());
		paramMap.put("goodsNormsValueId", paramOrderReturnRef.getNewOrderNormsValueId());
		resultMap = goodsNormsValueStockService.getNormsValueStockByMap(paramMap);
		goodsNormsStock = goodsNormsStockService.selectGoodsNormsStock(stockId);
		goodsNormsStock.setStockNum(goodsNormsStock.getStockNum() - paramOrderReturnRef.getReturnGoodsNum());
		goodsNormsStockService.updateGoodsNormsStock(goodsNormsStock);
//		
//		ordersFlowDao.insert("com.sayimo.school.mall.dao.ope.OrdersFlowDao.insertOrdersFlow", flow);
		ordersFlowInterfaceService.insertProviderOrdersFlow(flow);

		return orderId;
	}
	
	/** 
	  * @package com.sayimo.school.mall.service.ope.impl
	  * @author chenpy
	  * @Title:  
	  * @Description: 
	  * @param 
	  * @throws 
	  * @return String
	  * @date 2016年6月17日
	  */ 
	private String generateBatchCode() throws ServiceException {
		StringBuffer batchCode = new StringBuffer();
		char[] charArray = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
				'Y', 'Z' };
		Random random = new Random();
		String beforeTwoPlace = String.valueOf(charArray[random.nextInt(26)]) + String.valueOf(charArray[random.nextInt(26)]);
		Date nowDate = new Date();
		batchCode.append(beforeTwoPlace + String.valueOf(DateUtil.getYear(nowDate))
				+ String.valueOf(DateUtil.getMonth(nowDate) < 10 ? "0" + DateUtil.getMonth(nowDate) : DateUtil.getMonth(nowDate))
				+ String.valueOf(DateUtil.getDay(nowDate) < 10 ? "0" + DateUtil.getDay(nowDate) : DateUtil.getDay(nowDate))
				+ VerifyCodeUtil.getNumberVerifyCode(6));		
//		Integer count = ordersReceivingAddressService.queryOrdersReceivingCountByBatchCode(batchCode.toString());
		Integer count = ordersReceivingAddressInterfaceService.queryOrdersReceivingCountByBatchCode(batchCode.toString());
		if (count > 0) {
			logger.info("batchCode==" + batchCode + "重复，需重新生成");
			generateBatchCode();
		}
		return batchCode.toString();
	}
	/** 
	  * @package com.sayimo.school.mall.service.ope.impl
	  * @author chenpy
	  * @Title:  updatePrimitiveOrderInfo
	  * @Description: 修改原始订单信息（修改退换货商品状态、重新计算原订单金额）
	  * @param 
	  * @throws ServiceException 
	  * @throws DaoException 
	  * @throws 
	  * @return void
	  * @date 2016年6月21日
	  */ 
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public void updatePrimitiveOrderInfo(OrderReturnRef paramOrderReturnRef,Integer providerId) throws ServiceException, DaoException {
		// 查询原订单信息
//		List ordersGoodsInfos = ordersService.queryOrdersNormsInfoById(paramOrderReturnRef.getOrderId());
		List ordersGoodsInfos = ordersListInterfaceService.queryOrdersNormsInfoById(paramOrderReturnRef.getOrderId());
		if (CollectionUtils.isEmpty(ordersGoodsInfos)) {
			return;
		}
		
		Map<String, Object> firstOrderGoodsInfoMap = (Map<String, Object>) ordersGoodsInfos.get(0);
		Integer ordersGoodsStatus = paramOrderReturnRef.getType() == 1 ? 2 : 3;
	
		for (Object object : ordersGoodsInfos) {
			Map<String, Object> ordersGoodsInfoMap = (Map<String, Object>) object;
			Integer goodsId = Integer.parseInt(String.valueOf(ordersGoodsInfoMap.get("goodsId")));
			logger.info(goodsId + ", " + paramOrderReturnRef.getGoodsId());
			if (paramOrderReturnRef.getGoodsId() - goodsId != 0) {
				continue;
			}
			OrdersGoodsInfo goodsInfo = new OrdersGoodsInfo();
			Integer buyNum = Integer.parseInt(String.valueOf(ordersGoodsInfoMap.get("buyNum")));
			goodsInfo.setId(Integer.parseInt(String.valueOf(ordersGoodsInfoMap.get("id"))));
			Integer normGoodsNum = buyNum - paramOrderReturnRef.getReturnGoodsNum();
			// 该款商品已全部退换，则修改对应的订单下商品状态为“已退、换货”
			if (normGoodsNum == 0) { 
				goodsInfo.setStatus(ordersGoodsStatus);
			}
			goodsInfo.setBuyNum(buyNum - paramOrderReturnRef.getReturnGoodsNum());
			ordersGoodsInfoInterfaceService.updateOrderGoodsInfo(goodsInfo);
//			ordersGoodsInfoService.updateOrdersGoodsInfo(goodsInfo); 
		}
		
		OrdersList orders = new OrdersList();
		orders.setId(paramOrderReturnRef.getOrderId());
		
		// 判断订单状态
		if (ordersGoodsInfos.size() == 1) {
			ordersGoodsInfos = ordersListInterfaceService.queryOrdersNormsInfoById(paramOrderReturnRef.getOrderId());
			// 订单下商品已全部退换货
			if (CollectionUtils.isEmpty(ordersGoodsInfos)) {
				// 修改订单状态为“已完成”
				OrdersFlow flow = new OrdersFlow();
				flow.setActionUser(providerId);
				flow.setActionUserType(1);
				flow.setOrdersId(paramOrderReturnRef.getOrderId());
				flow.setStatus(7);
//				ordersFlowDao.insert("com.sayimo.school.mall.dao.ope.OrdersFlowDao.insertOrdersFlow", flow);
				ordersFlowInterfaceService.insertProviderOrdersFlow(flow);
				orders.setStatus(7);
			}
		}
		
		BigDecimal sumMoney = (BigDecimal) firstOrderGoodsInfoMap.get("sumMoney");
		BigDecimal totalAmount = (BigDecimal) firstOrderGoodsInfoMap.get("totalAmount");
		orders.setTotalAmount(totalAmount.subtract(paramOrderReturnRef.getTotalMoeny()));
		orders.setSumMoney(sumMoney.subtract(paramOrderReturnRef.getTotalMoeny()));
//		ordersService.updateOrdersById(orders);
		ordersListInterfaceService.updateOrdersById(orders);

	}
	
}
